define(['./module'],function(module){
	'use strict';

	module.controller('storecoupon',serverstorecouponctrl);
	function serverstorecouponctrl($stateParams,$http,$location,$compile,$scope,DTOptionsBuilder,DTColumnBuilder,Upload,$timeout){


		var vm = this;
		vm.message = '';
		vm.someClickHandler = someClickHandler;
		vm.selected = {};
		vm.selectAll = false;
		vm.toggleAll = toggleAll;
		vm.toggleOne = toggleOne;
		vm.dtInstance = {};
		var titleHtml = '<input type="checkbox" ng-model="gt.selectAll" ng-click="gt.toggleAll(gt.selectAll,gt.selected)">';
		vm.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
				type: 'POST',
				url: '../mall/storeinfo/findStoreByPage',
				dataSrc: 'data'
			})
			.withOption('processing', true)
			.withOption('paging', true)
			.withOption('serverSide', true)
			.withOption('createdRow', function (row, data, dataIndex) {
				$compile(angular.element(row).contents())($scope);
			})
			.withOption('headerCallback', function (header) {
				if (!$scope.headerCompiled) {
					$scope.headerCompiled = true;
					$compile(angular.element(header).contents())($scope);
				}
			})
			.withOption('stateSave', true)
			.withOption('rowCallback', rowCallback)
			.withPaginationType('full_numbers')
			.withLanguageSource('./app/language/chinese.json')

		$scope.$on('handleRequest', function () {

		});
		vm.dtColumns = [
			DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function (data, type, full, meta) {
				vm.selected[full.id] = false;
				return "<input type='checkbox' ng-model=\"gt.selected['" + data.id + "']\" ng-click=\"gt.toggleOne(gt.selected)\">";
			}),
			DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
			DTColumnBuilder.newColumn('storename').withTitle('店铺名称').notSortable(),
			DTColumnBuilder.newColumn('telno').withTitle('固定电话').notSortable(),
			DTColumnBuilder.newColumn('mobile').withTitle('移动电话').notSortable(),
			DTColumnBuilder.newColumn('master').withTitle('负责人').notSortable(),
			DTColumnBuilder.newColumn('companyname').withTitle('公司名称').notSortable(),
			DTColumnBuilder.newColumn('isreviewed').withTitle('审核状态').notSortable(),
			DTColumnBuilder.newColumn('status').withTitle('状态').notSortable(),
			DTColumnBuilder.newColumn('updatetime').withTitle('更新时间').notSortable()];

		function reloadData() {
			var resetPaging = false;
			vm.dtInstance.reloadData(callback, resetPaging);
		}

		function callback(data) {
		}


		/**
		 * 列表全选
		 */
		function toggleAll(selectAll, selectedItems) {
			for (var id in selectedItems) {
				if (selectedItems.hasOwnProperty(id)) {
					selectedItems[id] = selectAll;
				}
			}
		}

		/**
		 * 列表单选
		 */
		function toggleOne(selectedItems) {
			var me = this;
			for (var id in selectedItems) {
				if (selectedItems.hasOwnProperty(id)) {
					if (!selectedItems[id]) {
						me.selectAll = false;
					}
				}
			}
			me.selectAll = true;

		}

		function someClickHandler(info) {
			vm.message = info.id + ' - ' + info.name;
			$scope.pushToSelectedStores(info.id, info);
		}

		/**
		 * 单击列表某行回调
		 */
		function rowCallback(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
			$('td', nRow).unbind('click');
			$('td', nRow).bind('click', function () {
				$scope.$apply(function () {
					vm.someClickHandler(aData);
				});
			});
			return nRow;
		}


		//选定的专题货物

		$scope.pushToSelectedStores = function (index, store) {
			$scope.sp=[];
			$scope.sp.push(store);
			$scope.selectedstores=$scope.sp;
		};


		/**
		 * 删除选择的店铺
		 * @param index
		 */
		$scope.removeselectstore = function (index) {
			$scope.selectedstores.splice(index, 1);
			$scope.sp.slice(index,1);
		}




		$scope.$watch('rmainfiles', function () {
			$scope.uploadrmainfiles($scope.rmainfiles);
		});
		$scope.allrmainfiles = [];
		$scope.uploadrmainfiles = function (files) {
			if (files && files.length) {
				for (var i = 0; i < files.length; i++) {
					var file = files[i];
					var filename = files[i].name;
					if (!file.$error) {
						Upload.upload({
							url: '../mall/files/ajaxFileUploadsImgs',
							data: {
								file: file,
								filename: filename
							}
						}).progress(function (evt) {
							var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
							$scope.rmainprogress = progressPercentage;
						}).success(function (data, status, headers, config) {
							$timeout(function () {
								if (data.ifb.sucflag) {
									$scope.allrmainfiles.push(data.ifb);
								}
							});
						});
					}
				}
			}
		}

		$scope.removeallrmainfiles = function (index) {
			$scope.allrmainfiles.splice(index, 1);
		}


		//通过location中的operate参数区分操作行为
		var operate=$location.search().operate||$stateParams.operate;
		if(operate!=undefined&&operate=="save"){
			//控制保存按钮显示
			$scope.savebtn={show:true};
			$scope.title='添加店铺优惠券信息';
			$scope.status="1";
			$scope.rangetype="2";//设置店铺优惠券
			$scope.reservationtimeshow=true;

			//保存数据方法
			$scope.save=function(){
				if($scope.coupontitle==undefined){
					$scope.errors={
							show:true,
							msg:'请输入优惠券标题'
					}
					return false;
				}

				if($scope.reservationtime==undefined){
					$scope.errors={
						show:true,
						msg:'请选择优惠券有效时间段'
					}
					return false;
				}

				if($scope.money==undefined){
					$scope.errors={
							show:true,
							msg:'请输入优惠金额'
					}
					return false;
				}
				if($scope.limituseprice==undefined){
					$scope.errors={
							show:true,
							msg:'请输入最低使用金额'
					}
					return false;
				}

				if($scope.userangenote==undefined){
					$scope.errors={
						show:true,
						msg:'请输入使用范围说明'
					}
					return false;
				}

				if($scope.selectedstores.length==0){
					$scope.errors = {
						show: true,
						msg: '请选择店铺'
					}
					return false;
				}


				var mainimg = angular.toJson($scope.allrmainfiles);
				$http({
					method:'POST',
					url:'../mall/coupon/save',
					data:{
						'rangecontentid':$scope.selectedstores[0].id,
						'coupontitle':$scope.coupontitle,
						'reservationtime':$scope.reservationtime,
						'money':$scope.money,
						'limituseprice':$scope.limituseprice,
						'userangenote':$scope.userangenote,
						'rangetype':$scope.rangetype,
						'mainimg':mainimg,
						'status':$scope.status
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.info={
								show:true,
								msg:'店铺优惠券信息添加成功'
						}
						$location.path("/storecouponment");
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}
		
		}
		
		//如果operate是edit则执行保存行为
		if(operate=='edit'){
			var id=$location.search().id;
			if(id!=undefined&&id!=""){
				$http({
					method:'POST',
					url:'../mall/coupon/find',
					data:{
						'id':id
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.title='正在对店铺优惠券--'+data.bean.coupontitle+'--进行编辑';
						$scope.coupontitle=data.bean.coupontitle;
						$scope.reservationtimeshow=true;
						$scope.reservationtime=data.reservationtime;
						$scope.money=data.bean.money;
						$scope.limituseprice=data.bean.limituseprice;
						$scope.userangenote=data.bean.userangenote;
						$scope.rangetype=data.bean.rangetype;
						$scope.allrmainfiles.push(data.ifb);
						$scope.selectedstores = data.store;
						$scope.status=data.bean.status;
						$scope.updatebtn={show:true};
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
				//更新数据方法
				$scope.update=function(){
					if($scope.coupontitle==undefined){
						$scope.errors={
							show:true,
							msg:'请输入优惠券标题'
						}
						return false;
					}

					if($scope.reservationtime==undefined){
						$scope.errors={
							show:true,
							msg:'请选择优惠券有效时间段'
						}
						return false;
					}

					if($scope.money==undefined){
						$scope.errors={
							show:true,
							msg:'请输入优惠金额'
						}
						return false;
					}
					if($scope.limituseprice==undefined){
						$scope.errors={
							show:true,
							msg:'请输入最低使用金额'
						}
						return false;
					}

					if($scope.userangenote==undefined){
						$scope.errors={
							show:true,
							msg:'请输入使用范围说明'
						}
						return false;
					}

					if($scope.selectedstores.length==0){
						$scope.errors = {
							show: true,
							msg: '请选择店铺'
						}
						return false;
					}


					var mainimg = angular.toJson($scope.allrmainfiles);
					$http({
						method:'POST',
						url:'../mall/coupon/update',
						data:{
							'id':id,
							'rangecontentid':$scope.selectedstores[0].id,
							'coupontitle':$scope.coupontitle,
							'reservationtime':$scope.reservationtime,
							'money':$scope.money,
							'limituseprice':$scope.limituseprice,
							'userangenote':$scope.userangenote,
							'rangetype':$scope.rangetype,
							'mainimg':mainimg,
							'status':$scope.status
						}
					}).
					success(function(data,status,headers,config){
						if(data.sucflag){
							$scope.info={
									show:true,
									msg:'店铺优惠券信息更新成功'
							}
							$location.path("/storecouponment");
						}
					}).
					error(function(data,status,headers,config){
						$scope.errors={
								show:true,
								msg:'系统异常'
						}
					});
				}
			}
		
		}
	}



	module.controller('ModalInstanceCtrl', function ($uibModalInstance, items) {
		var ctrl = this;
		ctrl.items = items;
		ctrl.selected = {
			item: ctrl.items[0]
		};

		ctrl.ok = function () {

			$uibModalInstance.close(ctrl.selected.item);
		};

		ctrl.cancel = function () {
			$uibModalInstance.dismiss('cancel');
		};
	});


	module.controller('ModalDemoCtrl', function ($uibModal, $log, $document) {
		var ctrl = this;
		ctrl.items = ['item1', 'item2', 'item3'];

		ctrl.animationsEnabled = true;


		ctrl.open = function (size, parentSelector) {
			var parentElem = parentSelector ?
				angular.element($document[0].querySelector('.modal-demo ' + parentSelector)) : undefined;
			var modalInstance = $uibModal.open({
				animation: ctrl.animationsEnabled,
				ariaLabelledBy: 'modal-title',
				ariaDescribedBy: 'modal-body',
				templateUrl: 'myModalContent.html',
				controller: 'ModalInstanceCtrl',
				controllerAs: 'ctrl',
				size: size,
				appendTo: parentElem,
				resolve: {
					items: function () {
						return ctrl.items;
					}
				}
			});

			modalInstance.result.then(function (selectedItem) {
				ctrl.selected = selectedItem;
			}, function () {
				$log.info('Modal dismissed at: ' + new Date());
			});



		};

		ctrl.openComponentModal = function () {
			var modalInstance = $uibModal.open({
				animation: ctrl.animationsEnabled,
				component: 'modalComponent',
				resolve: {
					items: function () {
						return ctrl.items;
					}
				}
			});

			modalInstance.result.then(function (selectedItem) {
				ctrl.selected = selectedItem;
			}, function () {
				$log.info('modal-component dismissed at: ' + new Date());
			});
		};

		ctrl.openMultipleModals = function () {
			$uibModal.open({
				animation: ctrl.animationsEnabled,
				ariaLabelledBy: 'modal-title-bottom',
				ariaDescribedBy: 'modal-body-bottom',
				templateUrl: 'stackedModal.html',
				size: 'sm',
				controller: function($scope) {
					$scope.name = 'bottom';
				}
			});

			$uibModal.open({
				animation: ctrl.animationsEnabled,
				ariaLabelledBy: 'modal-title-top',
				ariaDescribedBy: 'modal-body-top',
				templateUrl: 'stackedModal.html',
				size: 'sm',
				controller: function($scope) {
					$scope.name = 'top';
				}
			});
		};

		ctrl.toggleAnimation = function () {
			ctrl.animationsEnabled = !ctrl.animationsEnabled;
		};
	});


	module.controller('storecouponment',serverstorecouponmentctrl);
	//查询列表数据
	function serverstorecouponmentctrl($uibModal,$log,$document,$http,$location,$compile,$scope,DTOptionsBuilder,DTColumnBuilder){

		$scope.title="店铺优惠券列表";
		var vm=this;
		vm.message='';
		vm.someClickHandler = someClickHandler;
		vm.selected={};
		vm.selectAll=false;
		vm.toggleAll=toggleAll;
		vm.toggleOne=toggleOne;
		vm.dtInstance={};
		var titleHtml='<input type="checkbox" ng-model="showCase.selectAll" ng-click="showCase.toggleAll(showCase.selectAll,showCase.selected)">';
		vm.dtOptions=DTOptionsBuilder.newOptions().withOption('ajax',{
			type:'POST',
			url:'../mall/coupon/findByPage',
			data:{
				'couponrangetype':"2"
			},
			dataSrc:'data'
		})
		.withOption('processing',true)
		.withOption('paging',true)
		.withOption('serverSide',true)
		.withOption('createdRow',function(row,data,dataIndex){
			$compile(angular.element(row).contents())($scope);
		})
		.withOption('headerCallback', function(header) {
            if (!$scope.headerCompiled) {
                $scope.headerCompiled = true;
                $compile(angular.element(header).contents())($scope);
            }
        })
        .withOption('stateSave', true)
        .withOption('rowCallback',rowCallback)
		.withPaginationType('full_numbers')
		.withLanguageSource('./app/language/chinese.json')
		
		$scope.$on('handleRequest',function(){
			
		});
		
		vm.dtColumns=[
		              DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function(data,type,full,meta){
		            	  vm.selected[full.id]=false;
		            	  return '<input type="checkbox" ng-model="showCase.selected['+data.id+']" ng-click="showCase.toggleOne(showCase.selected)">';
		              }),
		              DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
		              DTColumnBuilder.newColumn('coupontitle').withTitle('优惠券标题').notSortable(),
		              DTColumnBuilder.newColumn(null).withTitle('优惠图').notSortable().renderWith(imgHtml),
			          DTColumnBuilder.newColumn('rangetype').withTitle('优惠类型').notSortable(),
			          DTColumnBuilder.newColumn('time').withTitle('持续时间').notSortable(),
					  DTColumnBuilder.newColumn('limituseprice').withTitle('最小使用金额').notSortable(),
			DTColumnBuilder.newColumn('money').withTitle('优惠金额').notSortable(),
			DTColumnBuilder.newColumn('total').withTitle('总数量').notSortable(),
			DTColumnBuilder.newColumn('bindtotal').withTitle('绑定数量').notSortable(),
			          DTColumnBuilder.newColumn('status').withTitle('状态').notSortable(),
			          DTColumnBuilder.newColumn('updatetime').withTitle('更新时间').notSortable(),
			          DTColumnBuilder.newColumn('version').withTitle('版本号').notSortable(),
			          DTColumnBuilder.newColumn(null).withTitle('操作').notSortable().renderWith(actionHtml)];
		function imgHtml(data,type,full,meta){
			return '<img style="width:50px;height:50px;" ng-src="'+data.smainimg+'" alt="Photo" />';
		}
		function actionHtml(data,type,full,meta){
			return '<button class="btn btn-warning" ng-click="edit('+data.id+')"><i class="fa fa-edit"></i></button>'+
				'<button class="btn btn-warning" ng-click="couponcodement('+data.id+')">生成优惠码</button>';
		}
		
		function reloadData(){
			var resetPaging = false;
	        vm.dtInstance.reloadData(callback, resetPaging);
		}
		function callback(data){
		}



		/**
		 * 复杂搜索刷新数据
		 */
		function searchReloadData(){
			var resetPaging=false;
			var searchParams={
				isCustomSearch:1,
				name:''
			};
			if($scope.name!=undefined){
				searchParams.name=$scope.name;
				vm.dtOptions['ajax'].data=searchParams;
				vm.dtInstance.reloadData(callback, resetPaging);
			}
		}

		/**
		 * 表格
		 */
		$scope.searchdataTableCustom=function(){
			searchReloadData();
		}

		//表格中编辑按钮
		$scope.edit=function(id,name){
			$location.path('/storecoupon').search({'operate':'edit','id':id});
		}
		
		/**
		 * 跳转到添加商品类型和参数页面
		 */
		$scope.save=function(){
			$location.path('/storecoupon').search({'operate':'save'});
		}
		
		$scope.del=function(){
			var i=0;
			var ids=[];
			angular.forEach(vm.selected, function(data,index,array){
				if(data){
					i++;
					ids.push(index);
				}
			});
			if(i==0){
				$scope.errors={
						show:true,
						msg:'请选择一条记录'
				}
			}else{
				$scope.errors={
						show:false
				}
				//批量删除数据
				var idstrs=ids.join(",");
				$http({
					method:'POST',
					url:'../mall/coupon/del',
					data:{
						'id':idstrs
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.info={
								show:true,
								msg:'批量删除成功'
						}
						reloadData();
					}
					
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}
		}

		/**
		 * 列表全选
		 */
		function toggleAll(selectAll,selectedItems){
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					selectedItems[id]=selectAll;
				}
			}
		}
		/**
		 * 列表单选
		 */
		function toggleOne(selectedItems){
			var me=this;
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					if(!selectedItems[id]){
						me.selectAll=false;
					}
				}
			}
			me.selectAll=true;
		}

		function someClickHandler(info) {
	        vm.message = info.id + ' - ' + info.name;
	    }
		/**
		 * 单击列表某行回调
		 */
		function rowCallback(nRow,aData,iDisplayIndex,iDisplayIndexFull){
			$('td', nRow).unbind('click');
	        $('td', nRow).bind('click', function() {
	            $scope.$apply(function() {
	                vm.someClickHandler(aData);
	            });
	        });
	        return nRow;
		}
	}
});